<template>
  <div>
    <el-tag
      v-for="tag in selectUserList"
      :key="tag"
      class="mx-1"
      :closable="handleType !== 'view'"
      :disable-transitions="false"
      @close="deleteUser(tag)">
      {{ tag.userName }}
    </el-tag>
    <el-select
      ref="selectUserRef"
      v-if="selectUserVisible"
      value-key="label"
      filterable
      placeholder="请选择人员"
      size="small"
      style="width: 150px"
      @change="selectUserChange"
      @blur="selectUserVisible = false">
      <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item" />
    </el-select>
    <!-- <el-button v-else class="button-new-tag ml-1" size="small" @click="showUserSelect">
      <el-icon><CirclePlus /></el-icon>
    </el-button> -->
    <el-button v-else :icon="Plus" size="small" circle @click="showUserSelect" />
  </div>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const props = defineProps({
  userList: {
    type: Array,
    default: () => {
      return [
        // { userId: 1, userName: '李文兵' },
        // { userId: 2, userName: '张洋' },
      ]
    },
  },
  defaultSelectUserList: {
    type: Array,
    default: () => {
      return []
    },
  },
  only: {
    type: Boolean,
    default: false,
  },
  handleType: {
    type: String,
    default: '',
  },
})
const emit = defineEmits(['select'])
const selectUserList = ref([])
const selectUserIds = ref([])
watch(
  () => props.defaultSelectUserList,
  (val) => {
    if (val) {
      selectUserList.value = val
    }
  },
  { deep: true, immediate: true }
)
watch(
  () => selectUserList.value,
  (val) => {
    if (val) {
      emit('select', val)
      selectUserIds.value = val.map((obj) => obj.userId)
    }
  },
  { deep: true }
)
const selectUserVisible = ref(false)
const selectUserRef = ref()
/* 选择人员配置 */
// const userList = reactive()
// 选择人员
function selectUserChange(val) {
  if (selectUserIds.value.includes(val.userId)) {
    ElMessage.warning('已选择该人员')
    return
  }
  selectUserList.value.push(val)
  selectUserVisible.value = false
}
// 删除人员
function deleteUser(tag) {
  selectUserList.value.splice(selectUserList.value.indexOf(tag), 1)
}
function showUserSelect() {
  if (props.only && selectUserList.value.length === 1) {
    ElMessage.warning('仅可选一人')
    return
  }
  selectUserVisible.value = true
  nextTick(() => {
    selectUserRef.value.focus()
  })
}
</script>
<style></style>
